<template>
  <view class="container">
    <!-- 选择头像区域 -->
    <view class="input-container">
      <text class="input-label">头像：</text>
      <view class="avatar-field">
        <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar-btn">
          <image :src="avatarUrl || '/static/ava.png'" mode="aspectFill" class="avatar-img" @error="handleImageError" />
        </button>
      </view>
    </view>

    <!-- 昵称输入框 -->
    <view class="input-container">
      <text class="input-label">昵称：</text>
      <input class="input-field" type="nickname" :value="nickname" @input="handleInputChange" placeholder="请输入昵称" @click="hideKeyboard" />
    </view>

    <!-- 电话输入框 -->
    <view class="input-container">
      <text class="input-label">电话：</text>
      <input class="input-field" type="number" :value="tel" @input="handleTelChange" placeholder="请输入电话" />
    </view>

    <!-- 密码输入框 -->
    <view class="input-container">
      <text class="input-label">密码：</text>
      <input class="input-field" password :value="pass" @input="handlePassChange" placeholder="请输入密码" />
    </view>

    <!-- 注册并登录按钮 -->
    <button @click="authorizeLogin" class="login-btn">
      注册并登录
    </button>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { 
  uploadImage, 
  enrolls, 
  login,
  wxLogins
} from '/api/index.js'

// 响应式数据
const userInfo = ref({
  nickName: '',
  avatarUrl: ''
})
const nickname = ref('')
const openid = ref('')
const tel = ref('')
const pass = ref('')
const avatarUrl = ref('')
const isUploading = ref(false)

// 生命周期钩子
onMounted(() => {
  const storedUserInfo = uni.getStorageSync('userInfo')
  if (storedUserInfo) {
    userInfo.value = storedUserInfo
    nickname.value = storedUserInfo.nickName
    avatarUrl.value = storedUserInfo.avatarUrl
    
    const storedOpenid = uni.getStorageSync('openid')
    if (storedOpenid) {
      openid.value = storedOpenid
    }
    
    uni.navigateTo({
      url: '/pages/home/home'
    })
  }
  
  const localAvatarUrl = uni.getStorageSync('avatarUrl')
  if (localAvatarUrl) {
    avatarUrl.value = localAvatarUrl
    userInfo.value.avatarUrl = localAvatarUrl
  }
})

// 选择头像
const onChooseAvatar = async (e) => {
  const { avatarUrl: selectedAvatarUrl } = e.detail
  isUploading.value = true
  
  try {
    const result = await uploadImage(selectedAvatarUrl)
    if (result.url) {
      const serverAvatarUrl = 'https://yiliao.kuxia.top' + result.url
      avatarUrl.value = serverAvatarUrl
      userInfo.value.avatarUrl = serverAvatarUrl
      uni.setStorageSync('avatarUrl', serverAvatarUrl)
    } else {
      throw new Error('上传失败，服务器未返回URL')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    uni.showToast({
      title: '头像上传失败，请重试',
      icon: 'none'
    })
    avatarUrl.value = selectedAvatarUrl
    userInfo.value.avatarUrl = selectedAvatarUrl
  } finally {
    isUploading.value = false
  }
}

// 处理头像加载错误
const handleImageError = () => {
  avatarUrl.value = '/static/ava.png'
}

// 处理输入变化
const handleInputChange = (e) => {
  nickname.value = e.detail.value
  userInfo.value.nickName = e.detail.value
}
const handleTelChange = (e) => tel.value = e.detail.value
const handlePassChange = (e) => pass.value = e.detail.value

// 表单验证
const validateForm = () => {
  if (!userInfo.value.avatarUrl) {
    uni.showToast({ title: '请上传头像', icon: 'none' })
    return false
  }
  if (!nickname.value) {
    uni.showToast({ title: '请填写昵称', icon: 'none' })
    return false
  }
  if (!tel.value) {
    uni.showToast({ title: '请填写电话', icon: 'none' })
    return false
  }
  if (!pass.value) {
    uni.showToast({ title: '请填写密码', icon: 'none' })
    return false
  }
  return true
}

// 授权登录
const authorizeLogin = async () => {
  if (!validateForm()) return

  try {
    uni.showLoading({ title: '登录中...' })
    
    // 1. 获取微信code
    const loginRes = await uni.login()
    if (!loginRes.code) throw new Error('获取登录凭证失败')
    
    // 2. 获取openid和session_key
    const appid = 'wx3c0518fdc0f73347'
    const secret = 'ecec3ad8ba75497227d4dbf316c6c336'
    const sessionRes = await wxLogins({ 
      code: loginRes.code, 
      appid, 
      secret 
    })
    
    if (sessionRes.code !== 1) {
      throw new Error(sessionRes.message || '获取session_key失败')
    }
    
    openid.value = sessionRes.data.openid
    uni.setStorageSync('openid', openid.value)
    
    // 3. 提交用户信息
    await sendUserInfo()
    
  } catch (error) {
    console.error('登录过程出错:', error)
    uni.showToast({ 
      title: error.message || '操作失败，请重试', 
      icon: 'none',
      duration: 3000 
    })
  } finally {
    uni.hideLoading()
  }
}

// 提交用户信息
const sendUserInfo = async () => {
  const userData = {
    openid: openid.value,
    avatar: userInfo.value.avatarUrl,
    nickname: userInfo.value.nickName,
    tel: tel.value,
    pass: pass.value,
    sex: '1'
  };

  try {
    // 先尝试登录
    const loginRes = await login({ tel: tel.value, pass: pass.value });
    
    if (loginRes.code === 1) {
      handleLoginSuccess(loginRes)
    } else {
      // 账号不存在，调用注册接口
      const registerRes = await enrolls(userData);
      
      if (registerRes.code === 1) {
        // 注册成功后再次尝试登录
        const newLoginRes = await login({ tel: tel.value, pass: pass.value });
        
        if (newLoginRes.code === 1) {
          handleLoginSuccess(newLoginRes)
        } else {
          throw new Error('注册后登录失败，请重试')
        }
      } else {
        throw new Error(registerRes.message || '注册失败')
      }
    }
  } catch (error) {
    console.error('登录/注册过程出错:', error)
    uni.showToast({
      title: error.message || '操作失败，请重试',
      icon: 'none',
    })
  }
}

// 处理登录成功
const handleLoginSuccess = (response) => {
  if (!response || !response.data) {
    console.error('无效的响应数据:', response)
    throw new Error('无效的登录响应')
  }

  const userData = response.data
  const storedUserInfo = {
    nickName: userData.nickname || nickname.value || '',
    avatarUrl: userData.avatar || avatarUrl.value || '/static/ava.png'
  }
  
  // 存储用户信息到本地
  uni.setStorageSync('user', response)
  uni.setStorageSync('userInfo', storedUserInfo)
  
  console.log('用户信息已存储:', storedUserInfo)
  
  uni.showToast({
    title: "登录成功",
    icon: "success",
    duration: 2000,
  })

  setTimeout(() => {
    uni.reLaunch({
      url: "/pages/home/home",
    })
  }, 2000)
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

.input-container {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 20px;
  padding: 0 10px;
  box-sizing: border-box;
}

.input-label {
  width: 20%;
  font-size: 16px;
  color: #333;
}

.input-field {
  flex: 1;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 0 10px;
  font-size: 16px;
}

.avatar-field {
  flex: 1;
  display: flex;
  align-items: center;
}

.avatar-btn {
  width: 50px;
  height: 50px;
  border-radius: 10%;
  overflow: hidden;
  background-color: #f0f0f0;
  justify-content: center;
  margin-left: 10px;
  border: none;
}

.avatar-img {
  width: 50px;
  height: 50px;
  margin-left: -15px;
}

.login-btn {
  width: 80%;
  height: 45px;
  background-color: #13AF12;
  color: white;
  font-weight: 700;
  font-size: 18px;
  margin-top: 20px;
  border: none;
}
</style>